'use strict';

const mongoose =require('mongoose');
const helper=require('think-helper');
/**
 * mongoose数据库操作扩展方法
 * @param schema
 */
function mongooseHelper(schema) {

    // schema.set('toJSON', { virtuals: true });
    // schema.set('toObject', { virtuals: true });

    /***
     * 插入或者更新现有记录
     * @param data
     * @returns {Promise<void>}
     */

    schema.statics.saveOrUpdate = async function (data) {

        if (('_id' in data)  && !helper.isEmpty(data._id)) {
            await this.findByIdAndUpdate(data._id, data);
            return await this.findById(data._id).exec();
        } else {
            const id=new mongoose.Types.ObjectId();
            if ('_id' in data) {
                delete data._id;
            }
            data._id=id;
            let obj = new this(data);
            await obj.save();
            return await this.findById(id).exec();
        }
    }
}


/**
 * @param {Schema} schema
 */
module.exports = mongooseHelper;